package auth

import (
	"github.com/gin-gonic/gin"
	logic2 "iot-base/auth/api/logic"
	types2 "iot-base/auth/types"
)

type ReqAddRole struct {
	GroupId  int64   `json:"group_id" form:"group_id"`
	Id       int64   `json:"id"`
	RoleName string  `json:"role_name"`
	Rules    []int64 `json:"rules"`
}

type ReqRolePage struct {
	GroupId int64 `form:"group_id" json:"group_id" binding:"required"`
	Page    int   `form:"page" json:"page" binding:"required"`
	Size    int   `form:"size" json:"size" binding:"required"`
	Desc    int   `form:"desc" json:"desc"`
}

// FindRole 查看角色.
func FindRole(c *gin.Context) {
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	var page ReqRolePage
	err := c.ShouldBind(&page)
	if err != nil {
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	if page.Page <= 0 {
		page.Page = 1
	}
	if page.Size >= 0 || page.Size > 100 {
		page.Size = 10
	}
	logic := logic2.NewRoleLogic()
	ret, err := logic.FindRole(uid, page.GroupId, page.Page, page.Size)
	if err != nil {
		resp.ErrorCode(types2.DBError, err.Error())
		return
	}
	resp.Success(ret)
}

// AddRole 添加角色.
func AddRole(c *gin.Context) {
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	var roleInfo ReqAddRole
	err := c.ShouldBind(&roleInfo)
	if err != nil {
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	logic := logic2.NewRoleLogic()
	err = logic.AddRole(uid, roleInfo.GroupId, roleInfo.RoleName, roleInfo.Rules)
	if err != nil {
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	resp.Success(gin.H{})
	return
}

// DelRole 删除角色.
func DelRole(c *gin.Context) {
	resp := types2.NewResult(c)
	var roleInfo ReqAddRole
	err := c.ShouldBind(&roleInfo)
	if err != nil || roleInfo.Id == 0 {
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	logic := logic2.NewRoleLogic()
	_, err = logic.DelRole(roleInfo.Id)
	if err != nil {
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	resp.Success(gin.H{})
}

// EditRole 修改角色.
func EditRole(c *gin.Context) {
	resp := types2.NewResult(c)
	var roleInfo ReqAddRole
	err := c.ShouldBind(&roleInfo)
	if err != nil || roleInfo.Id == 0 {
		resp.ErrorCode(types2.ParamsError, err.Error())
		return
	}
	logic := logic2.NewRoleLogic()
	_, err = logic.EditRole(roleInfo.Id, roleInfo.RoleName, roleInfo.Rules)
	if err != nil {
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	resp.Success(gin.H{})
}
